﻿@inject AppState AppState

<ContentPage @ref="contentPage">
	<StackLayout Margin="20" VerticalOptions="LayoutOptions.StartAndExpand">
		<Label Text="Edit todo item details"
			   FontAttributes="FontAttributes.Bold"
			   FontSize="30" />
		<StackLayout Orientation="StackOrientation.Vertical">
			<Label Text="Done?" />
			<Switch @bind-IsToggled="ItemCopy.IsDone" />
		</StackLayout>
		<Entry @bind-Text="ItemCopy.Text" MinimumHeightRequest="60" />
		<Label Text="Additional notes" />
		<Entry @bind-Text="ItemCopy.Notes" MinimumHeightRequest="60" />
		<Button Text="Save"
				OnClick="OnSaveClick" BackgroundColor="Colors.Blue" TextColor="Colors.White" />
		<Button Text="Delete"
				OnClick="OnDeleteClick" BackgroundColor="Colors.Red" TextColor="Colors.White" />
		<Button Text="Cancel"
				OnClick="OnCancelClick" />
		<Button Text="Speak"
				OnClick="OnSpeakClick" />
	</StackLayout>
</ContentPage>

@code
{
	Microsoft.MobileBlazorBindings.Elements.ContentPage contentPage;

	[Parameter] public TodoItem Item { get; set; }

	private TodoItem ItemCopy { get; set; }

	protected override void OnInitialized()
	{
		base.OnInitialized();

		// Make a copy for editing purposes
		ItemCopy = new TodoItem
			{
				ID = Item.ID,
				IsDone = Item.IsDone,
				Text = Item.Text,
				Notes = Item.Notes,
			};
	}

	public async Task OnSaveClick()
	{
		// On save, copy the edited data back to the original
		Item.ID = ItemCopy.ID;
		Item.IsDone = ItemCopy.IsDone;
		Item.Text = ItemCopy.Text;
		Item.Notes = ItemCopy.Notes;

		await AppState.TodoDatabase.SaveItemAsync(Item);

		await contentPage.PopModalAsync();
	}

	public async Task OnDeleteClick()
	{
		await AppState.TodoDatabase.DeleteItemAsync(Item);

		await contentPage.PopModalAsync();
	}

	public async Task OnCancelClick()
	{
		await contentPage.PopModalAsync();
	}

	public async Task OnSpeakClick()
	{
		await TextToSpeech.SpeakAsync(Item.Text + " " + Item.Notes);
	}
}
